@page "/playground/new-account"
@using Microsoft.Extensions.Options
@using Passwordless.AdminConsole.Middleware
@using Passwordless.AdminConsole.Services.PasswordlessManagement
@inject ICurrentContext CurrentContext
@inject IOptionsSnapshot<PasswordlessManagementOptions> Options
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery
@model NewAccountModel

@{
    ViewData["Title"] = "Playground";
    var requestToken = Antiforgery.GetAndStoreTokens(Model.HttpContext).RequestToken;
}

<div>
    <div class="flex flex-1 flex-col justify-center lg:flex-non bg-gray-200 rounded-md p-6 max-w-fit">
        <div class="w-full max-w-sm lg:w-96">
            <div>
                <h2 class="text-2xl font-bold tracking-tight text-gray-900">Register new user</h2>
                <p class="mt-2 text-sm text-gray-600">
                    Please use the form below to create your new account.
                </p>
            </div>

            <div class="mt-8">
                <div class="mt-6">
                    <form id="registration-form">
                        <fieldset id="registerCredentialFields" class="space-y-6">
                            <div>
                                <label for="name" class="block text-sm font-medium leading-6 text-gray-900">Name (Visible in Browser UI)</label>
                                <div class="mt-2">
                                    <input type="text" name="name" id="name" required class="text-input">
                                </div>
                            </div>
                            <div>
                                <label for="email" class="block text-sm font-medium leading-6 text-gray-900">Email address / Username (Visible in Browser UI)</label>
                                <div class="mt-2">
                                    <input id="email" name="email" type="text" required class="text-input">
                                </div>
                            </div>

                            <div>
                                <label for="nickname" class="block text-sm font-medium leading-6 text-gray-900">Nickname for this device (optional)</label>
                                <div class="mt-2">
                                    <input asp-for="Nickname" type="text" name="nickname" id="nickname" class="text-input">
                                    <span asp-validation-for="Nickname"></span>
                                </div>
                            </div>

                            <div>
                                <label class="block text-sm font-medium leading-6 text-gray-900">Attestation</label>
                                <div class="mt-2 flex">
                                    <div class="flex-1 radio-control">
                                        <input asp-for="Attestation" type="radio" name="attestation" id="attestation-none" class="radio-input" value="none"/>
                                        <label for="attestation-none" class="radio-label">None</label>
                                    </div>
                                    @if (CurrentContext.Features.AllowAttestation)
                                    {
                                        <div class="flex-1 radio-control">
                                            <input asp-for="Attestation" type="radio" name="attestation" id="attestation-direct" class="radio-input" value="direct" />
                                            <label for="attestation-direct" class="radio-label">Direct</label>
                                        </div>
                                        <div class="flex-1 radio-control">
                                            <input asp-for="Attestation" type="radio" name="attestation" id="attestation-indirect" class="radio-input" value="indirect"/>
                                            <label for="attestation-indirect" class="radio-label">Indirect</label>
                                        </div>
                                    }
                                    else
                                    {
                                        <div class="flex-1 radio-control">
                                            <input type="radio" name="attestation" id="attestation-direct" class="radio-input" disabled="disabled" />
                                            <label for="attestation-direct" class="radio-label">Direct</label>
                                        </div>
                                        <div class="flex-1 radio-control">
                                            <input type="radio" name="attestation" id="attestation-indirect" class="radio-input" disabled="disabled" />
                                            <label for="attestation-indirect" class="radio-label">Indirect</label>
                                        </div>
                                    }
                                    <span asp-validation-for="Attestation"></span>
                                </div>
                                @if (!CurrentContext.Features.AllowAttestation)
                                {
                                    <warning-alert-box message="@((MarkupString)"Attestation is only available on 'Enterprise' plans, read more <a class=\"link-blue\" href=\"https://docs.passwordless.dev/guide/concepts.html#attestation\" target=\"_blank\">here</a>.")"></warning-alert-box>
                                }
                            </div>

                            <div>
                                <label for="hints" class="block text-sm font-medium leading-6 text-gray-900">Credential hints (optional)</label>
                                <div class="mt-2">
                                    <input asp-for="Hints" type="text" name="hints" id="hints" class="text-input">
                                    <span asp-validation-for="Hints"></span>
                                </div>
                            </div>

                            <div>
                                <button id="register-btn" class="btn-primary" type="button">Register</button>
                            </div>

                            <div id="error-message-summary-container" class="hidden">
                                <danger-alert-box></danger-alert-box>
                            </div>
                        </fieldset>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let p;
document.addEventListener('DOMContentLoaded', function() {
    p = new Passwordless.Client({
        apiUrl: "@Options.Value.ApiUrl",
        apiKey: "@CurrentContext.ApiKey"
    });
});

document.getElementById('register-btn').addEventListener('click', (e) => createNewAccount(e));

const createNewAccount = async (e) => {
    const form = document.getElementById("registration-form");
    const data = new FormData(form);

    // Validation
    if (data.get("hints")) {
        const hints = data.get("hints").split(",").map(h => h.trim().toLowerCase());

        if (new Set(hints).size !== hints.length) {
            alert("You cannot provide duplicate hints.");
            return;
        }

        if (!hints.every(h => ["client-device", "security-key", "hybrid"].includes(h))) {
            alert("Hint values must be either 'client-device', 'security-key', or 'hybrid'.");
            return;
        }
    }

    const res = await fetch("?handler=token", {
        method: "post",
        body: data,
        headers: {
            RequestVerificationToken: "@requestToken"
        }
    });

    if (res.ok) {
        const { token } = await res.json();
        const nicknameForDevice = data.get("nickname");
        const { error } = await p.register(token, nicknameForDevice);

        if (error) {
            console.error(error);
            alert(error.title);
        }

        window.location.href = "../playground";
    } else {
        const container = document.getElementById("error-message-summary-container");
        const field = container.getElementsByClassName("alert-box-message")[0];
        const problemDetails = await res.json();
        field.textContent = problemDetails.title;
        container.classList.remove("hidden");
    }
}

const isSupported = Passwordless.isBrowserSupported();
if (!isSupported) {
    const registerCredentialFields = document.getElementById("registerCredentialFields");
    registerCredentialFields.disabled = true;

    const container = document.getElementById("error-message-summary-container");
    const field = container.getElementsByClassName("alert-box-message")[0];
    field.textContent = "WebAuthn is not supported in this browser.";
    container.classList.remove("hidden");
}
</script>

